package com.ruoyi.asset.service.impl;

import com.ruoyi.flowable.domain.WorkOrderAssetRel;
import com.ruoyi.flowable.mapper.WorkOrderAssetRelMapper;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工单资产关联Service业务层处理
 */
@Service
public class WorkOrderAssetRelServiceImpl implements IWorkOrderAssetRelService {

    private static final Logger log = LoggerFactory.getLogger(WorkOrderAssetRelServiceImpl.class);

    @Autowired
    private WorkOrderAssetRelMapper workOrderAssetRelMapper;

    /**
     * 根据ID查询
     */
    @Override
    public WorkOrderAssetRel selectWorkOrderAssetRelById(Long id) {
        return workOrderAssetRelMapper.selectWorkOrderAssetRelById(id);
    }

    /**
     * 查询列表
     */
    @Override
    public List<WorkOrderAssetRel> selectWorkOrderAssetRelList(WorkOrderAssetRel workOrderAssetRel) {
        return workOrderAssetRelMapper.selectWorkOrderAssetRelList(workOrderAssetRel);
    }

    /**
     * 新增
     */
    @Override
    public int insertWorkOrderAssetRel(WorkOrderAssetRel workOrderAssetRel) {
        // 检查是否已存在相同的流程实例记录
        WorkOrderAssetRel existing = workOrderAssetRelMapper.selectByProcInsId(workOrderAssetRel.getProcInsId());
        if (existing != null) {
            log.warn("工单记录已存在，procInsId: {}", workOrderAssetRel.getProcInsId());
            return 0;
        }

        workOrderAssetRel.setCreateTime(new Date());
        workOrderAssetRel.setUpdateTime(new Date());
        return workOrderAssetRelMapper.insertWorkOrderAssetRel(workOrderAssetRel);
    }

    /**
     * 修改
     */
    @Override
    public int updateWorkOrderAssetRel(WorkOrderAssetRel workOrderAssetRel) {
        workOrderAssetRel.setUpdateTime(new Date());
        return workOrderAssetRelMapper.updateWorkOrderAssetRel(workOrderAssetRel);
    }

    /**
     * 删除
     */
    @Override
    public int deleteWorkOrderAssetRelById(Long id) {
        return workOrderAssetRelMapper.deleteWorkOrderAssetRelById(id);
    }

    /**
     * 根据流程实例ID查询
     */
    @Override
    public WorkOrderAssetRel selectByProcInsId(String procInsId) {
        return workOrderAssetRelMapper.selectByProcInsId(procInsId);
    }

    /**
     * 根据资产ID查询工单记录
     */
    @Override
    public List<WorkOrderAssetRel> selectByAssetId(Long assetId) {
        return workOrderAssetRelMapper.selectByAssetId(assetId);
    }

    /**
     * 根据流程实例ID列表批量查询
     */
    @Override
    public List<WorkOrderAssetRel> selectByProcInsIds(List<String> procInsIds) {
        return workOrderAssetRelMapper.selectByProcInsIds(procInsIds);
    }

    /**
     * 根据流程实例ID列表批量查询(map)
     */
    @Override
    public Map<String, WorkOrderAssetRel> getMapByProcInstIds(List<String> procInsIds) {
        List<WorkOrderAssetRel> records = workOrderAssetRelMapper.selectByProcInsIds(procInsIds);
        return records.stream()
                .collect(Collectors.toMap(WorkOrderAssetRel::getProcInsId, record -> record));
    }

    /**
     * 根据流程实例ID删除记录
     */
    @Override
    public int deleteByProcInsId(String procInsId) {
        return workOrderAssetRelMapper.deleteByProcInsId(procInsId);
    }

    /**
     * 根据资产ID删除记录
     */
    @Override
    public int deleteByAssetId(Long assetId) {
        return workOrderAssetRelMapper.deleteByAssetId(assetId);
    }

    /**
     * 更新工单状态
     */
    @Override
    public int updateWorkOrderStatus(String procInsId, String workOrderStatus, Date finishTime) {
        return workOrderAssetRelMapper.updateWorkOrderStatus(procInsId, workOrderStatus, finishTime);
    }

    /**
     * 更新预计完成时间
     */
    @Override
    public int updatePlanFinishTime(String procInsId, Date planFinishTime) {
        return workOrderAssetRelMapper.updatePlanFinishTime(procInsId, planFinishTime);
    }

    /**
     * 更新资产信息
     */
    @Override
    public int updateAssetInfo(String procInsId, Long assetId, String assetName, String assetNumber) {
        return workOrderAssetRelMapper.updateAssetInfo(procInsId, assetId, assetName, assetNumber);
    }

    /**
     * 查询我的工单列表
     */
    @Override
    public List<WorkOrderAssetRel> selectMyWorkOrders(Long userId, String status, String procDefName, String assetName) {
        return workOrderAssetRelMapper.selectMyWorkOrders(userId, status, procDefName, assetName);
    }

    /**
     * 批量新增工单资产关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsertWorkOrderAssetRel(List<WorkOrderAssetRel> workOrderAssetRelList) {
        int count = 0;
        Date now = new Date();

        for (WorkOrderAssetRel workOrderAssetRel : workOrderAssetRelList) {
            // 检查是否已存在
            WorkOrderAssetRel existing = workOrderAssetRelMapper.selectByProcInsId(workOrderAssetRel.getProcInsId());
            if (existing != null) {
                log.warn("跳过已存在的工单记录，procInsId: {}", workOrderAssetRel.getProcInsId());
                continue;
            }

            workOrderAssetRel.setCreateTime(now);
            workOrderAssetRel.setUpdateTime(now);
            count += workOrderAssetRelMapper.insertWorkOrderAssetRel(workOrderAssetRel);
        }
        return count;
    }

    /**
     * 根据流程实例ID批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDeleteByProcInsIds(List<String> procInsIds) {
        int count = 0;
        for (String procInsId : procInsIds) {
            count += workOrderAssetRelMapper.deleteByProcInsId(procInsId);
        }
        return count;
    }

    /**
     * 完成工单（业务方法）
     */
    public int completeWorkOrder(String procInsId) {
        return updateWorkOrderStatus(procInsId, "completed", new Date());
    }

    /**
     * 驳回工单（业务方法）
     */
    public int rejectWorkOrder(String procInsId) {
        return updateWorkOrderStatus(procInsId, "rejected", new Date());
    }

    /**
     * 检查工单是否存在
     */
    public boolean existsWorkOrder(String procInsId) {
        WorkOrderAssetRel rel = selectByProcInsId(procInsId);
        return rel != null;
    }
}
